﻿
using Microsoft.EntityFrameworkCore;

namespace 并发控制
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            //抢房子的并发控制


            Console.WriteLine("请你的姓名：");
            string name = Console.ReadLine();
            using (var db = new MyContext())
            {

                var h1 = db.Houses.Single(h => h.Id == 2);
                if (string.IsNullOrEmpty(h1.Owner))
                {
                    await Task.Delay(5000);
                    h1.Owner = name;
                    try
                    {
                        await db.SaveChangesAsync();
                        Console.WriteLine("抢到手了");
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        var entry = ex.Entries.First();
                        var dbValues = await entry.GetDatabaseValuesAsync();
                        string newOwner = dbValues.GetValue<string>(nameof(House.Owner));
                        Console.WriteLine($"并发冲突，被{newOwner}提前抢走了");
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    if (h1.Owner == name)
                    {
                        Console.WriteLine("这个房子已经是你的了，不用抢");
                    }
                    else
                    {
                        Console.WriteLine($"这个房子已经被{h1.Owner}抢走了");
                    }
                }
                Console.ReadLine();
            }

            //修改价格的并发控制

            /*            

            Console.WriteLine("请输入新的价格");
            double newPrice = Convert.ToDouble(Console.ReadLine());
            using (var db = new MyContext())
            {
                var h1 = db.Houses.Single(h => h.Id == 2);
                if (h1.Price != newPrice)
                {
                    await Task.Delay(5000);
                    h1.Price = newPrice;
                    try
                    {
                        await db.SaveChangesAsync();
                        Console.WriteLine("价格修改成功");
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        var entry = ex.Entries.First();
                        var dbValues = await entry.GetDatabaseValuesAsync();
                        double currentPrice = dbValues.GetValue<double>(nameof(House.Price));
                        Console.WriteLine($"并发冲突，当前价格已经被修改为{currentPrice}");
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    Console.WriteLine("价格没有变化，不用修改");
                }
                Console.ReadLine();
            }
            */


            //RowVersion并发控制：代码和上面一样，只是配置不同


        }
    }
}
